<script setup>
import { storeToRefs } from 'pinia';
// import { useUrl } from '~~/composables/states';
useHead({
    title: 'HLS: Распределение',
})
const mpp = useCookie('mpp');
const user = useCookie('user');
if (user.value == null) {
    navigateTo('/login');
}
const naryads_rasp = useNaryadListRasp();
const naryads = storeToRefs(naryads_rasp);
// const filterPodr = ref(0);
const one_etap_rasp = useOneEtapRasp();
const sort_by = ref('');
const naryad_search = ref('');

const storePodrList = usePodrListAll();
const { podrList, setPodr } = storePodrList;
const { podrSelected } = storeToRefs(storePodrList);

const urlHome = useUrl();
const isOpen = ref(false);
const modal_number_nar = ref('');
const modal_stu_nar = ref('');
const modal_patient_nar = ref('');
const brigadeChangeStore = useStBrigadeNar();
const { raspList, setStatus } = brigadeChangeStore;
const { status } = storeToRefs(brigadeChangeStore);
const statusRef = ref('')
statusRef.value = status.value;

const pend = ref('');
pend.value = false;

const idkvModal = ref(0);

const select_all = ref(false);

const { pending, data: narList, refresh: narListUpdate } = await useFetch(`${urlHome.value}lab/nar_list/`, {
    lazy: true,
    query: {
        mpp: mpp.value,
        status: status, // st or st_change_brigade
    },
    watch: [status],
})

async function statusChange() {
    await setStatus(statusRef.value);
}

// narListUpdate();

// let intervalId

// onMounted(() => {
//     narListUpdate()
//     intervalId = setInterval(narListUpdate, 1000 * 60 * 2)
// })

// onUnmounted(() => clearInterval(intervalId))

const { data: uslModal } = await useFetch(`${urlHome.value}lab/pl_uslp_list`, {
    immediate: false,
    watch: [idkvModal],
    query: {
        idkv: idkvModal,
    }
})

const narsFiltered = computed(() => narList?.value?.filter((item) => item.patient.fam.toLowerCase().includes(naryad_search.value?.toLowerCase()) && (podrSelected.value == 0 || item.lpu.lpu == podrSelected.value)))

async function moveTo(id, sdl, index) {
    const { data: next_etap_status } = await useAsyncData('next_etap_status', () => $fetch(urlHome.value + 'naryad/next_etap/' + id + '/' + sdl + '/True' + '/' + mpp.value))
    if (next_etap_status._rawValue.status == 'ok') {
        naryads_rasp.removeAnElement(index);
    }
    if (next_etap_status._rawValue.status == 'exist') {
        alert('Такой этап уже есть');
        naryads_rasp.removeAnElement(index);
    }
}

async function getUsl(idkv, nkv, stu, fam, im, ot) {
    idkvModal.value = idkv
    console.log(idkv, idkvModal.value)
    modal_number_nar.value = nkv;
    modal_stu_nar.value = stu;
    modal_patient_nar.value = fam + ' ' + im + ' ' + ot;
    isOpen.value = true;
    return;
}

function sortNaryadList(sortBy) {
    switch (sortBy) {
        case 'dnaz_etap_inc':
            naryads.naryads.value.sort(function (a, b) {
                return (new Date(a.dou)) - (new Date(b.dou));
            });
            break;
        case 'dnaz_etap_desc':
            naryads.naryads.value.sort(function (a, b) {
                return (new Date(b.dou)) - (new Date(a.dou));
            });
            break;
        case 'stu_inc':
            naryads.naryads.value.sort(function (a, b) {
                return a.stu - b.stu;
            });
            break;
        case 'stu_desc':
            naryads.naryads.value.sort(function (a, b) {
                return b.stu - a.stu;
            });
            break;
    }
    return;
}

async function toNaryad(index, id) {
    console.log("index:", index, "id:", id)
    console.log("one_etap:", narList.value[index])
    one_etap_rasp.naryad.value = narList.value[index];
    await navigateTo('/lab/naryad_st/' + id);
}

function resetSearch() {
    naryad_search.value = '';
    sort_by.value = '';
    podrSelected.value = 0;
    sort_by.value = '';
    narListUpdate();
}

</script>

<style>
.list-complete-item {
    transition: all 0.8s ease;
    display: inline-block;
    margin-right: 10px;
}

.list-complete-enter-from,
.list-complete-leave-to {
    opacity: 0;
    transform: translateY(30px);
}

.list-complete-leave-active {
    position: absolute;
}
</style>

<template>
    <div>
        <div class="px-2 py-2 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-3
            2xl:grid-cols-3 sm:flex md:flex lg:flex xl:flex 2xl:flex sm:gap-4">
            <UInput type="text" color="primary" placeholder="Фамилия пациента" v-model="naryad_search" />
            <!-- <USelect color="green" v-model="sort_by" :options="sort_list" option-attribute="name"
                    @change="sortNaryadList(sort_by)" /> -->
            <USelect color="primary" v-model="podrSelected" :options="podrList" value-attribute="value" />
            <USelect color="primary" v-model="statusRef" @change="statusChange" :options="raspList" />
            <UButton v-if="naryad_search != '' || sort_by != ''" label="Очистить" @click="resetSearch" />
        </div>
        <div v-if="pending">
            <LoadFetchAnimation></LoadFetchAnimation>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3" v-auto-animate>
            <div v-for="( item, index ) in narsFiltered" :key="item.nkv">
                <div>
                    <NaryadListNaryadCard :getUsl="getUsl" :item="item" :toNaryad="toNaryad" :moveTo="moveTo"
                        :index="index" />
                </div>
            </div>
        </div>
        <UModal v-model="isOpen" :ui="{ base: 'max-w-6xl', width: '' }">
            <UCard :ui="{ divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
                <template #header>
                    <div
                        class="grid grid-cols-1 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-3 sm:flex md:flex lg:flex xl:flex 2xl:flex sm:gap-4">
                        <div class="text-2xl ">Наряд : <b>{{ modal_number_nar }}</b></div>
                        <div class="text-2xl ">Сумма : <b>{{ modal_stu_nar }} ₽</b></div>
                        <div class="text-1xl align-middle">Пациент : {{ modal_patient_nar }}</div>
                    </div>
                </template>
                <div class="overflow-x-auto relative">
                    <div class="flex flex-row w-full">
                        <div class="basis-1/4"><b>Код</b></div>
                        <div class="basis-1/4"><b>Кол-во</b></div>
                        <div class="basis-1/4 text-right"><b>Цена</b></div>
                        <div class="basis-1/4 text-right"><b>Сумма</b></div>
                    </div>
                    <hr>
                    <div v-for="( item, index ) in uslModal" :key="item.kusl">
                        <div>
                            <div class="flex flex-row w-full">
                                <div class="basis-1/4"><b>{{ item.kusl }}</b></div>
                                <div class="basis-1/4"><b>{{ item.kol }}</b></div>
                                <div class="basis-1/4 text-right"><b>{{ (item.price).toLocaleString() }} ₽</b></div>
                                <div class="basis-1/4 text-right"><b>{{ (item.stu).toLocaleString() }} ₽</b></div>
                            </div>

                            <!-- <div v-if="index % 2 == 0" class="break-words">{{ item.nusl }}</div> -->
                            <div class="break-words">{{ item.nusl }}</div>
                        </div>
                        <hr>
                    </div>
                </div>

                <template #footer>
                    <UButton @click="isOpen = false" label="Закрыть" />
                </template>
            </UCard>
        </UModal>
    </div>
</template>
